package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.Complaint;
import com.hanserwei.community.entity.po.Owner;
import com.hanserwei.community.entity.request.complaint.ComplaintQueryRequest;
import com.hanserwei.community.entity.request.complaint.ComplaintSaveRequest;
import com.hanserwei.community.entity.vo.ComplaintVO;
import com.hanserwei.community.entity.vo.OwnerBriefVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.ComplaintMapper;
import com.hanserwei.community.service.ComplaintService;
import com.hanserwei.community.service.OwnerService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, Complaint> implements ComplaintService {

    private final OwnerService ownerService;

    @Override
    public Page<ComplaintVO> pageComplaints(ComplaintQueryRequest request) {
        Page<Complaint> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<Complaint> wrapper = buildQueryWrapper(request);
        Page<Complaint> complaintPage = page(page, wrapper);
        List<ComplaintVO> voList = convertToVOList(complaintPage.getRecords());
        Page<ComplaintVO> voPage = new Page<>(complaintPage.getCurrent(), complaintPage.getSize(), complaintPage.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public ComplaintVO getComplaintDetail(Integer id) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "投诉记录ID参数错误！");
        Complaint complaint = getById(id);
        ThrowUtils.throwIf(complaint == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "投诉记录不存在！");
        List<ComplaintVO> vos = convertToVOList(Collections.singletonList(complaint));
        return vos.isEmpty() ? null : vos.get(0);
    }

    @Override
    public boolean createComplaint(ComplaintSaveRequest request) {
        validateSaveRequest(null, request);
        Complaint complaint = new Complaint();
        BeanUtils.copyProperties(request, complaint);
        boolean result = save(complaint);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateComplaint(Integer id, ComplaintSaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "投诉记录ID参数错误！");
        validateSaveRequest(id, request);
        Complaint complaint = getById(id);
        ThrowUtils.throwIf(complaint == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "投诉记录不存在！");
        BeanUtils.copyProperties(request, complaint);
        complaint.setId(id);
        boolean result = updateById(complaint);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public QueryWrapper<Complaint> buildQueryWrapper(ComplaintQueryRequest request) {
        QueryWrapper<Complaint> wrapper = new QueryWrapper<>();
        if (request == null) {
            return wrapper;
        }
        wrapper.eq(request.getId() != null && request.getId() > 0, "id", request.getId());
        wrapper.like(StringUtils.hasText(request.getComplaintCode()), "com_id", request.getComplaintCode());
        wrapper.eq(request.getOwnerId() != null && request.getOwnerId() > 0, "owner_id", request.getOwnerId());
        wrapper.eq(request.getStatus() != null, "status", request.getStatus());
        wrapper.ge(request.getComplaintTimeFrom() != null, "com_date", request.getComplaintTimeFrom());
        wrapper.le(request.getComplaintTimeTo() != null, "com_date", request.getComplaintTimeTo());
        wrapper.ge(request.getHandleTimeFrom() != null, "handle_date", request.getHandleTimeFrom());
        wrapper.le(request.getHandleTimeTo() != null, "handle_date", request.getHandleTimeTo());
        wrapper.like(StringUtils.hasText(request.getRemarks()), "remarks", request.getRemarks());
        if (StringUtils.hasText(request.getOwnerName())) {
            List<Integer> ownerIds = ownerService.lambdaQuery()
                    .like(Owner::getUserName, request.getOwnerName())
                    .select(Owner::getId)
                    .list()
                    .stream()
                    .map(Owner::getId)
                    .distinct()
                    .toList();
            if (ownerIds.isEmpty()) {
                wrapper.apply("1 = 0");
            } else {
                wrapper.in("owner_id", ownerIds);
            }
        }
        wrapper.orderBy(StringUtils.hasText(request.getSortField()), !"descend".equalsIgnoreCase(request.getSortOrder()), request.getSortField());
        return wrapper;
    }

    private void validateSaveRequest(Integer id, ComplaintSaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(request.getOwnerId() == null || request.getOwnerId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "投诉业主不能为空！");
        Owner owner = ownerService.getById(request.getOwnerId());
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "投诉业主不存在！");
        if (StringUtils.hasText(request.getComplaintCode())) {
            Long duplicate = lambdaQuery()
                    .eq(Complaint::getComplaintCode, request.getComplaintCode())
                    .ne(id != null && id > 0, Complaint::getId, id)
                    .count();
            ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "投诉编号已存在！");
        }
        LocalDateTime complaintTime = request.getComplaintTime();
        ThrowUtils.throwIf(complaintTime == null, ResponseCodeEnum.INVALID_PARAMETER, "投诉时间不能为空！");
        LocalDateTime handleTime = request.getHandleTime();
        if (complaintTime != null && handleTime != null) {
            ThrowUtils.throwIf(complaintTime.isAfter(handleTime), ResponseCodeEnum.INVALID_PARAMETER, "处理时间不能早于投诉时间！");
        }
    }

    private List<ComplaintVO> convertToVOList(List<Complaint> complaints) {
        if (CollectionUtils.isEmpty(complaints)) {
            return Collections.emptyList();
        }
        Set<Integer> ownerIds = complaints.stream()
                .map(Complaint::getOwnerId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Integer, Owner> ownerMap = ownerIds.isEmpty() ? Collections.emptyMap() : ownerService.listByIds(ownerIds).stream()
                .collect(Collectors.toMap(Owner::getId, owner -> owner));

        return complaints.stream().map(complaint -> {
            ComplaintVO vo = new ComplaintVO();
            BeanUtils.copyProperties(complaint, vo);
            vo.setComplaintCode(complaint.getComplaintCode());
            vo.setOwnerId(complaint.getOwnerId());
            if (complaint.getOwnerId() != null) {
                Owner owner = ownerMap.get(complaint.getOwnerId());
                if (owner != null) {
                    vo.setOwner(toOwnerBrief(owner));
                }
            }
            return vo;
        }).toList();
    }

    private OwnerBriefVO toOwnerBrief(Owner owner) {
        if (owner == null) {
            return null;
        }
        return OwnerBriefVO.builder()
                .id(owner.getId())
                .name(owner.getUserName())
                .tel(owner.getTel())
                .houseId(owner.getHouseId())
                .build();
    }
}
